//
//  MNDBackMoneyContentCell.m
//  minidai
//
//  Created by Steven.Yung on 2017/9/28.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDBackMoneyContentCell.h"
#import "MNDReturnListCell.h"
#import "MNDAdvancedReturnListCell.h"
#import "MNDReturnListSectionModel.h"
#import "MNDBackMoneyHeaderView.h"
#import "NSDate+JKExtension.h"

@interface MNDBackMoneyContentCell () <UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong) NSMutableArray *returnList;
@property (weak, nonatomic) UIView *blankView;

@end

@implementation MNDBackMoneyContentCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.tableView.tableFooterView = [UIView new];
    
    self.tableView.estimatedRowHeight = 120;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (void)setDateTime:(NSString *)dateTime {
    _dateTime = dateTime;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM";
    
    NSDate *date = [formatter dateFromString:dateTime];
    
    self.dateLabel.text = [NSString stringWithFormat:@"%zd年%02zd月", date.jk_year, date.jk_month];
}

- (void)setReturnListModel:(MNDReturnListModel *)returnListModel {
    _returnListModel = returnListModel;
    
    if (returnListModel == nil) {
        [self.contentView beginLoading];
    } else {
        [self.contentView endLoading];
    }
    
    self.returnTotalMoneyLabel.text = returnListModel.month_return_total;
    self.incomeTotalMoneyLabel.text = returnListModel.month_return_income;
    
    NSDictionary *returnLists = returnListModel.user_return_list;
    
    [self creatMaskView:!returnLists.count];
    
    [self.returnList removeAllObjects];
    
    NSArray *dates = [returnLists.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
        
    }];
    
    NSMutableArray *reverArr = [NSMutableArray array];
    //按日期排序
    for (NSInteger i = 0; i < dates.count; i ++) {
        
        NSString *date = dates[i];
        NSArray *detailList = [MNDReturnDayDetailModel mj_objectArrayWithKeyValuesArray:returnLists[date][@"list"]];
        
        MNDReturnListSectionModel *sectionModel = [MNDReturnListSectionModel new];
        sectionModel.dayString = date;
        sectionModel.returnMoney = returnLists[date][@"days_rerurn_sum"];
        sectionModel.dayList = detailList;
        sectionModel.isExpand = NO;
        
        [reverArr addObject:sectionModel];
        
    }
    if (!self.isUnReturn) {
        self.returnTotalTitleLabel.text = @"已回总额";
        self.incomeTotalTitleLabel.text = @"已收收益";
        //倒叙排列
        [self.returnList addObjectsFromArray:[[reverArr reverseObjectEnumerator] allObjects]];
    } else {
        self.returnTotalTitleLabel.text = @"待回总额";
        self.incomeTotalTitleLabel.text = @"待收收益";
        [self.returnList addObjectsFromArray: reverArr];
    }
    
    [self.tableView reloadData];
}

- (void)creatMaskView:(BOOL)isEmpty {
    if (!isEmpty) {
        if (self.blankView) {
            [self.blankView removeFromSuperview];
        }
        return;
    }
    if (self.blankView) {
        return;
    }
    UIView *maskView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, self.contentView.bounds.size.height)];
    maskView.backgroundColor = kColorF5;
    [self.contentView addSubview:maskView];
    
    [maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.trailing.equalTo(self.contentView);
    }];

    UIImageView *imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"back_money_empty"]];
    [maskView addSubview:imgV];
    
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(maskView);
        make.bottom.equalTo(maskView.mas_centerY);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.text = self.isUnReturn ? @"您本月没有待回款数据哦~" : @"您本月没有回款哦~";
    label.font = [UIFont systemFontOfSize:14.0];
    label.textColor = kColorGray;
    [maskView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imgV);
        make.top.equalTo(imgV.mas_bottom).offset(20);
    }];
    
    self.blankView = maskView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.returnList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MNDReturnListSectionModel *model = self.returnList[section];
    
    return model.isExpand ? model.dayList.count : 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 103.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    static NSString *const identifier = @"header";
    
    MNDBackMoneyHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
    
    if (!headerView) {
        headerView = [[MNDBackMoneyHeaderView alloc] initWithReuseIdentifier:identifier];
    }
    
    WeakSelf(self);
    
    MNDReturnListSectionModel *model = self.returnList[section];
    headerView.model = model;
    
    headerView.headerClickedBlock = ^(BOOL expand) {
        [weakself updateTableViewSection:section];
    };
    
    return headerView;
}

- (void)updateTableViewSection:(NSInteger)section {
    //    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    //    [self.tableView endUpdates];
}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = tableView.backgroundColor;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNDReturnListSectionModel *sectionModel = self.returnList[indexPath.section];
    NSArray *array = sectionModel.dayList;
    MNDReturnDayDetailModel *dayModel = array[indexPath.row];
    
    if (dayModel.is_advance_return.integerValue == 1) {
        static NSString *const cellidentifier = @"advanceCell";
        MNDAdvancedReturnListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [cell configCellWithModel: dayModel];
        return cell;
    } else {
        static NSString *const cellIdentifier = @"cell";
        
        MNDReturnListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell configCellWithModel:dayModel];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MNDReturnListSectionModel *sectionModel = self.returnList[indexPath.section];
    NSArray *array = sectionModel.dayList;
    MNDReturnDayDetailModel *dayModel = array[indexPath.row];
    
    NSLog(@"tenderid: %@", dayModel.tender_id);
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectedWithTenderId:)]) {
        [self.delegate didSelectedWithTenderId:[NSString stringWithFormat:@"%@", dayModel.tender_id]];
    }
}

- (NSMutableArray *)returnList {
    if (!_returnList) {
        _returnList = [NSMutableArray array];
    }
    
    return _returnList;
}

@end
